import mitt from 'mitt';

type Handler = (data: any) => void;
const handlers = {};

export const bus = mitt();

/**
 * 广播事件
 *
 * @export
 * @param {string} type
 * @param {*} [data]
 */
export function broadcast(type: string, data?: any) {
	bus.emit(type, data);
}

/**
 * 监听事件
 *
 * @export
 * @param {string} type
 * @param {Handler} handler
 * @returns {() => void} 移除监听回调
 */
export function listen(type: string, handler: Handler): () => void {
	bus.on(type, handler);

	return () => {
		unlisten(type, handler);
	};
}

/**
 * 移除监听
 *
 * @export
 * @param {string} type
 * @param {Handler} [handler] 为空时，默认移除所有监听
 */
export function unlisten(type: string, handler?: Handler) {
	if (handler) bus.off(type, handler);
}
